package com.leyou.order.interceptor;

import com.leyou.common.pojo.UserInfo;
import com.leyou.common.utils.CookieUtils;
import com.leyou.common.utils.JwtUtils;
import com.leyou.order.config.JwtProperties;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * lcd  2020/6/16
 * Description:
 */
@Slf4j
public class UserInterceptor implements HandlerInterceptor {
    //可以保证线程安全
    private static final ThreadLocal<UserInfo> tl = new ThreadLocal<>();
    private JwtProperties properties;

    public UserInterceptor(JwtProperties properties) {
        this.properties = properties;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        String token = CookieUtils.getCookieValue(request, properties.getCookieName());
        try {
            UserInfo userInfo = JwtUtils.getInfoFromToken(token, properties.getPublicKey());
            //传递User
//            request.setAttribute("user", userInfo);
            tl.set(userInfo);
            return true;
        } catch (Exception e) {
            log.error("[购物车服务]解析用户jwt信息失败", e);
            return false;
        }
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        tl.remove();
    }

    public static UserInfo get() {
        return tl.get();
    }
}
